<template>
  <!-- 头以下 -->
  <div class="layout-col flex2">
    <div class="ww100 flex-bc mb10 white">
      <div class="flex-sc">
        <span>当前任务：</span>
        <el-select class="flex1" v-model="state.taskId" placeholder="请选择任务" size="large" style="width: 100%;">
          <el-option v-for="item in state.taskList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </div>
      <div class="flex-ec flex1 h32">
        <img class="ml5 cursor" src="@/assets/images/e1.png" @click="state.styleType = '2'">
        <img class="ml5 cursor" src="@/assets/images/e2.png" @click="state.styleType = '4'">
        <img class="ml5 cursor" src="@/assets/images/e3.png" @click="state.styleType = '9'">
        <span class="i21 cursor ml20" @click="toPath('/controllog')">操作记录</span>
      </div>
    </div>
    <div v-if="!state.empty" class="ww100 flex1 overlay tc flex-ss warp hidden">
      <div v-for="(v, i) in state.list.filter(a=>!state.type || a.type == state.type)" :key="i" 
      class="borderstyle relative p20 rad10 bs hidden flex-col" 
      :class="state.styleType=='2'?'list2-15':state.styleType=='4'?'list3-15':'list4-15'" 
      style="box-sizing: border-box;"
      element-loading-background="rgba(0, 0, 0, 0.3)"
      v-loading="v.loading? true : false"
      element-loading-text="遥控中...">
        <div class="absolute t20 r20 cursor ww18" v-if="v.action && !isNull(v.action.kgArr)" @click.stop="remote(v, 'kg')">
          <img v-if="v.kg == 0" class="ww100" src="@/assets/images/icon1.png">
          <img v-if="v.kg == 1" class="ww100" src="@/assets/images/icon11.png">
        </div>
        <div class="flex-col ww100">
          <div class="flex-sc"><div :class="v.offline != 0?'bga':'bgi21'" class="rad100 w10 h10 mt2 mr8"></div>{{v.name}}</div>
          <div class="flex-sc mt10 ml18">
            <div class="mr8">位置:</div>
            <div>{{v.instlPos}}</div>
          </div>
        </div>
        <div class="flex-bc ww100 flex1">
          <div class="flex1 flex-cc" :class="v.offline != 0?'gray':''">
            <img class="ww50" src="@/assets/images/door.png" v-if="v.type=='access_ctrl' && v.kg == 0">
            <img class="ww50" src="@/assets/images/door2.png" v-else-if="v.type=='access_ctrl' && v.kg == 1">
          </div>
        </div>
      </div>
    </div>
    <div v-if="state.empty" class="flex1 tc flex-cc fw f30">设置类型控制点</div>
  </div>
</template>

<script lang="ts" setup>
  import api from '@/api'
  import scheduled from "@/utils/scheduled";
  const { createScheduled } = scheduled();
  const { proxy }: any = getCurrentInstance();
  const configStore = proxy.configStore();
  const publicStore = proxy.publicStore();
  const state = reactive({
    ...publicStore.$state,
    clickIndex: '-1',
    styleType: '2',
    typeList: [],
    type: '',
    initParams: {},
    taskList: [],
    taskId: '',
  });

  onMounted(async () => {
    await getInit()
    init()
    getTask()
    createScheduled('lock', 1*1000, () => { init() })
  });

  watch([() => publicStore.isTrue, () => configStore.user], async (val) => {
    getTask()
  },{ immediate: false, deep: true });

  const getInit = async() => {
    let query = {"o": "o_sensor", "p": [publicStore.distributId], "i": 0}
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    let sensorList = proxy.isNull(res)? [] : res
    let query2 = getQuery(sensorList)
    let params2 = {queryApi2: query2}
    let res2 = await publicStore.post(params2)
    state.typeList = getTypeList(res2)
    state.list = getList(res)
    state.empty = proxy.isNull(state.list)? true : false
    getParams()
    init()
  }

  const getQuery = (val) => {
    let tempArr = [] 
    val.filter(a=>a.class == 0).forEach(v => {
      let exist = tempArr.find(a=>a.p[0] == v.type)
      if(!exist) tempArr.push({"o":"o_sensor_template_control_property","p":[v.type]})
    })
    return tempArr
  }

  const getTypeList = (val, val2) => {
    let tempArr = [{name: '全部', type: ''}]
    val.forEach(v => {
      let exist = tempArr.find(a=>a.type == v.sensor_type)
      if(!exist && v.sensor_type == 'access_ctrl') tempArr.push({name: proxy.find(configStore.templateList, ['type', v.sensor_type], 'name'), type: v.sensor_type})
    })
    return tempArr
  }

  const getList = (val) => {
    let tempArr = [] 
    state.typeList.forEach(v => {
      let list = val.filter(a=> a.type == v.type)
      if(list) tempArr = tempArr.concat(list)
    })
    return tempArr
  }

  const getParams = async() => {
    let queryArr1 = []
    let queryArr2 = []
    let queryArr3 = []
    state.list.forEach(v => {
      let query1 = {"o": "o_sensor_control_action", "p":[v.id], "i": 0}
      let query2 = {"o":"o_r_sensor", "p":[v.id], "i": 1}
      let query3 = {"o":"o_sensor_cfg_property", "p":[v.id], "i": 0}
      queryArr1.push(query1)
      queryArr2.push(query2)
      queryArr3.push(query3)
    })
    state.initParams = {queryApi1: queryArr1, queryApi2: queryArr2, queryApi3: queryArr3}
  }
 
  const init = async() => { 
    let res = await publicStore.post(state.initParams)
    let queryApi1 = proxy.isNull(res.queryApi1)? [] : res.queryApi1
    let queryApi2 = proxy.isNull(res.queryApi2)? [] : res.queryApi2
    let queryApi3 = proxy.isNull(res.queryApi3)? [] : res.queryApi3
    state.list.forEach(v => {
      let action = queryApi1.filter(a=>a.sensor_id == v.id)
      let r_sensor = queryApi2.find(a=>a.sensor_id == v.id)
      let cfg_sensor = queryApi3.filter(a=>a.sensor_id == v.id)
      v = Object.assign(v, r_sensor)
      v.action = !proxy.isNull(action)? setAction(action) : []
      let tempArr = setValue(cfg_sensor, r_sensor)
      v.valArr = !proxy.isNull(r_sensor) && !proxy.isNull(cfg_sensor)? tempArr[0] : []
      v.dwArr = !proxy.isNull(r_sensor) && !proxy.isNull(cfg_sensor)? tempArr[1] : []
      v.kg = v['doorState']? v['doorState'] : ''
      v.mode = v['6160']? v['6160'] : ''
    })
    console.log('state.list', state.list)
    publicStore.list = state.list
    getRemote()
  }

  const setAction = (action) => {
    // 开关action_type => kg 
    // 计数action_type => count
    // 模式action_type => mode
    let kgArr = []
    let countArr = []
    let modeArr = []
    action.forEach(v => {
      if(v.action_type.indexOf('kg') != -1) kgArr.push(v)
      if(v.action_type.indexOf('count') != -1) countArr.push(v)
      if(v.action_type.indexOf('mode') != -1) modeArr.push(v)
    })
    return {kgArr: kgArr, countArr: countArr, modeArr: modeArr}
  }

  const setValue = (cfg_sensor, r_sensor) => {
    let valArr = []
    let dwArr = []
    cfg_sensor.forEach(v => {
      if(v.code.indexOf('vc_') != -1) valArr.push(v.value)
      if(v.code.indexOf('dw_') != -1) dwArr.push(v.value)
    })
    valArr.forEach((v, i) => {
      valArr[i] = r_sensor[v]?Math.round(r_sensor[v]*100)/100 : ''
    });
    return [valArr, dwArr]
  }

  const getRemote = async() => {
    if(proxy.isNull(state.list)) return
    let remoteList = state.list.filter(a=>a.time && a.timeNum > 0 && a.remote)
    remoteList.forEach(v => {
      v.timeNum = v.timeNum - 1
      if(v.timeNum > 0){
        if(proxy.isNull(v.doorState_tc) || parseInt(v.doorState_tc) < v.time) return
        ElNotification({ title: '提示', message: v.name + '遥控成功', type: 'success' })
        setRecord(v, v.remote.value, 1)
        setTask(v, v.remote.remark)
        v.time = ''
        v.timeNum = 0
        v.remote = ''
      }else{
        ElNotification({ title: '提示', message: v.name + '遥控超时', type: 'error' })
        setRecord(v, v.remote.value, 2)
        console.log('超时失败-----', v, v.remote.value)
        v.time = ''
        v.timeNum = 0
        v.remote = ''
      }
    })
    console.log('remoteList', remoteList)
  }

  const remote = async(val, remark, value = '') => {
    publicStore.current = state.taskList.find(a=>a.id == state.taskId)
    if(proxy.isNull(configStore.user)) return ElNotification({ title: '提示', message: '请完成登录', type: 'error' })
    if(proxy.isNull(publicStore.current)) return ElNotification({ title: '提示', message: '请开始任务', type: 'error' })
    if(val.id != publicStore.current.sensor_id) return ElNotification({ title: '提示', message: '门禁已被指定', type: 'error' })
    let userIds = publicStore.current.userId.split(',')
    if(configStore.user.function_role!='1' && !userIds.find(a=>a == configStore.user.id)) return ElNotification({ title: '提示', message: '操作人员已被指定，请重新登录', type: 'error' })
    if(val.doorState == '0' && parseInt(publicStore.current.start_time) > new Date().getTime()) return ElNotification({ title: '提示', message: '未到开门时间', type: 'error' })
    if(val.doorState == '0' && parseInt(publicStore.current.end_time) < new Date().getTime()) return ElNotification({ title: '提示', message: '已超过开门时间', type: 'error' })
    if(publicStore.current.num == 0 && val[remark] == 0) return ElNotification({ title: '提示', message: '无开门次数', type: 'error' })
    state.clickIndex = val.id
    state.loading = true
    console.log('val----------', val, 'remark----------', remark)
    if(remark == 'kg') value = val.action[remark + 'Arr'].find(a=>a.action != val[remark])
    if(remark == 'count') value.action = value.action == 'add'? parseInt(val.valArr[0]) + 1 + '': value.action == 'redu'? parseInt(val.valArr[0]) - 1 + '' : '0'
    console.log('遥控value', value)
    value.startTime = new Date().getTime()
    let params = {sensor_id: value.sensor_id, code: value.code, action: value.action }
    val.loading = true
    api.remote([params]).then((res:any) => {
      if(res.errcode == 0){
        // 已发出遥控命令
        val.time = new Date().getTime()
        val.timeNum = 10
        val.remote = { remark: remark, value: value }
      }else{
        val.time = ''
        val.timeNum = 0
        val.remote = ''
        setRecord(val, value, 2)
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
      }
    }).catch((err) => {
        val.time = ''
        val.timeNum = 0
        val.remote = ''
        setRecord(val, value, 2)
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }

  const setRecord = async(val, value, res) => {
    val.loading = false
    let form = {
      id: new Date().getTime(),
      sensor_id: val.id,
      sensor_name: val.name,
      instlPos: val.instlPos,
      stationNum: publicStore.distributId,
      code: value.code,
      code_name: value.code_name,
      action: value.action,
      action_name: value.name,
      orther: '',
      userName: configStore.user.name,
      startTime: value.startTime,
      endTime: new Date().getTime(),
      result: res,
      o: 'o_sensor_control_log',
      a: '新增',
      t: 'add',
    }
    api.updateApi([form]).then((res:any) => {
      if(res.errcode == 0){
        console.log('遥控记录----------', res)
      }
    }).catch((err) => {
      ElNotification({ title: '提示', message: '记录失败', type: 'error' })
    })
  }

  const getTask = async() => {
    let query = ''
    if(!proxy.isNull(configStore.user) && configStore.user.function_role != '1'){
      query = {"o": "o_sensor_access", "p": [publicStore.distributId, '1', configStore.user.id], "i": 5}
    }else{
      query = {"o": "o_sensor_access", "p": [publicStore.distributId, '1'], "i": 1}
    }
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    state.taskList = proxy.isNull(res)? [] : res
    state.taskId = proxy.isNull(state.taskList)? '' : state.taskList[0].id
  }

  const setTask = async(val, remark) => {
    if(publicStore.current.num == '-1') return
    let form = Object.assign({}, publicStore.current)
    form.num = parseInt(publicStore.current.num) - 1
    form.status = '2'
    form.o = 'o_sensor_access'
    form.t = 'upd'
    form.a = '更新'
    console.log('form', form)
    api.updateApi([form]).then((res) => {
      if(res.errcode == 0){
        console.log('更新任务记录----------', res)
        ElNotification({ title: '提示', message: '任务完成', type: 'success' })
        publicStore.isTrue = !publicStore.isTrue
      }
    })
  }

  </script>
  
  <style scoped lang="scss">
    .tabStyle{
      background: linear-gradient(0deg, #242DAB 1%, rgba(12,1,67,0.00) 100%);
      border-bottom: 2px solid rgba(65, 255, 255, 0.5);
    }
    .textStyle{
      background: linear-gradient(180deg, #ffffff 0%, #64DEFF 100%);
      background-clip: text;
      -webkit-text-fill-color: transparent;
      box-sizing: border-box;
    }
  </style>
  